package com.ronri.ams.sample;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.entList;
import com.ronri.common.StringManager;
import com.ronri.common.UrlEncode;
import com.ronri.common.WaitDialog;
import com.ronri.db.RemoteDataService;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cz.nongyetongv5.application.InitApplication.gSampleInfo;


/**
 * 文件：ams.java
 * 包名：com.ronri.ams.sample;
 * 说明：
 * 作者：MS During
 * 日期：2017/6/21
 * 历史：
 */
public class activity_search_map extends abstract_activity {


    private Context mContext = null;

    // 列表控件
    private ListView mListView = null;

    // 查询输入框
    private EditText mFindKeys = null;

    // 执行查询按钮
    private TextView mbtnSearch = null;

    // 上一页
    private TextView mbtnPrev = null;

    // 下一页
    private TextView mbtnNext = null;

    // 数据源
    private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();

    // 远程服务器地址
    private String mRemoteAddress = null;

    // 当前页面编号
    private int mPageIndex = 1;

    // 总页数
    private int mPages = 10;

    // 分页行数
    private int mPageCount = 0;

    // 远程数据
    private RemoteDataService mRemoteDB = new RemoteDataService();

    // 关键字名
    private String mKeyName = "key";

    // 获取标题名称
    private String mKeyTitleName = "";

    // 选择模式
    private int mSelectMode = ListView.CHOICE_MODE_SINGLE;

    private String mJson = null;

    // 选择的行信息
    private List<Integer> mSelectItems = new ArrayList<Integer>();

    private Button mbtPageDown = null;
    private Button mbtPageUp = null;

    private int mKind;
    private int mTrade;
    private String mRegion;
    /***
     * 设置参数
     *
     * @param szRemoteAddress
     * @param szFindKey
     * @param szKeyTitleName
     */
    protected void setParamets(String szRemoteAddress, String szFindKey, String szKeyTitleName) {
        mKeyName = szFindKey;
        mRemoteAddress = szRemoteAddress;
        mKeyTitleName = szKeyTitleName;
    }

    /****
     * 列表适配器
     */
    class ListAdapter extends BaseAdapter {

        List<entList.DataBean.RowsBean> mItems = null;

        public ListAdapter(List<entList.DataBean.RowsBean> item) {
            mItems = item;
        }

        @Override
        public int getCount() {
            return mItems.size();
        }

        @Override
        public Object getItem(int i) {
            return mItems.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            if (view == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.venterprise_info, viewGroup, false);

                view.setTag(mItems.get(i));

                //对于listview，注意添加这一行，即可在item上使用高度
                AutoUtils.autoSize(view);
            }
            TextView title = (TextView)view.findViewById(R.id.vtitle);
            TextView humen = (TextView)view.findViewById(R.id.vhumen);
            TextView telphone = (TextView)view.findViewById(R.id.vtelphone);

            title.setText(mItems.get(i).getName());
            humen.setText(mItems.get(i).getCharge());
            telphone.setText(mItems.get(i).getTel());
            return view;
        }
    }

    private void getRemoteData(String szRegionCode, int kind, int trade, int nIndex) {

        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
//        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
//                InitApplication.SystemConfig.getModule().getEnlist().getAddress());

        String szRemoteAddress="http://120.55.93.238:8080/ams/api/entList.json";

        if (StringManager.InitString(szRegionCode).isEmpty()) {
            szRegionCode = InitApplication.LoginInfo.getData().getRegion_code();
        }

        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("page", nIndex);
            mParam.put("pageSize", 10);
            mParam.put("region_code", szRegionCode);
            //mParam.put("range", 5);
            mParam.put("kind", kind);
            mParam.put("trade", trade);
            mParam.put("ent_name", "");

        } catch (Exception ex) {

        }
        Log.i("test","szRemoteAddress-->"+szRemoteAddress);
        Log.i("test","mParam-->"+mParam.toString());
        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getEnlist().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    @Override
                    public void OnResultEvent(String szString) {
                        if (StringManager.InitString(szString).isEmpty()) {
                            return;
                        }
                        Log.i("test","szString-->"+szString);
                        if(szString.contains("网络连接失败")){
                            Toast.makeText(activity_search_map.this,"网络连接失败",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        entList ent = JSON.parseObject(szString,entList.class);
                        // 转义
                        // entListbean ent = JSON.parseObject(szString, entListbean.class);

                        if (ent.isSuccess()) {
                            mPageIndex = ent.getData().getPage();
                            // 设置总数
                            mPageCount = ent.getData().getTotal();
                            final List<entList.DataBean.RowsBean> items = ent.getData().getRows();

                            if (items.size() > 0) {

                                // 刷新数据
                                if (mListView != null) {

                                    ListAdapter adapter = new ListAdapter(items);
                                    mListView.setAdapter(null);
                                    mListView.setAdapter(adapter);
                                    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                                            Log.i("test","onItemClick2");
                                            entList.DataBean.RowsBean item= (entList.DataBean.RowsBean) items.get(i);
                                            if (item != null){
                                                Intent intent = new Intent();
                                                Bundle bundle = new Bundle();

                                                bundle.putString("name", item.getName());
                                                bundle.putString("humen", item.getCharge());
                                                bundle.putString("tel", item.getTel());
                                                bundle.putInt("id", item.getId());

                                                intent.putExtras(bundle);

                                                setResult(RESULT_OK, intent);
                                                finish();
                                            }
                                        }
                                    });

                                    // 选择模式
                                    mListView.setChoiceMode(mSelectMode);
                                    mListView.setAdapter(adapter);
                                }
                            }
                        } else {
                            // 提示失败
                        }
                    }

                    @Override
                    public void OnRuningState(int nStatus) {
                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                            WaitDialog.ShowDialog(mContext, "请稍后...");
                        } else {
                            WaitDialog.HideDialog();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                });
    }

    /***
     * 创建内容
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        Log.i("aaa","activity_search_map");
        mContext = this;

        Bundle bundle = getIntent().getExtras();
        mKind = bundle.getInt("kind");
        mTrade = bundle.getInt("trade");
        mRegion = bundle.getString("regioncode");

        // 显示标题与右边功能
        setTitle("选择企业", "");

        // 初始化内容
        init();

        mListView = (ListView) findViewById(R.id.lvDataItem);

        mbtPageDown = (Button)findViewById(R.id.btnPageDown);
        mbtPageUp = (Button)findViewById(R.id.btnPageUp);

        //上一页
        mbtPageUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mPageIndex==1){
                    Toast.makeText(activity_search_map.this,"已是第一页", Toast.LENGTH_SHORT).show();
                }else{
                    getRemoteData(mRegion, mKind, mTrade, mPageIndex - 1);
                }
            }
        });

        //下一页
        mbtPageDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPageIndex == mPageCount) {
                    Toast.makeText(activity_search_map.this,"没有更多数据", Toast.LENGTH_SHORT).show();
                }else{
                    getRemoteData(mRegion, mKind, mTrade, mPageIndex + 1);
                }

            }
        });

        getRemoteData(mRegion, mKind, mTrade, mPageIndex);
    }

    @Override
    public boolean CancelReturn() {
        setResult(RESULT_CANCELED);
        return super.CancelReturn();
    }

    /***
     * 数据提交
     *
     * @return
     */
    @Override
    public boolean SureReturn() {

        String szSplit = "";
        String szResult = "";

        szResult = "";
        for (Integer iTem : mSelectItems) {
            Map<String, Object> map = mItems.get(iTem);
            String szJson = (String) map.get("selectValue");
            szResult = szResult + szSplit + szJson;
            szSplit = ",";
        }

        if (szResult != "") {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("returnValue", "[" + szResult + "]");

            intent.putExtras(bundle);

            setResult(RESULT_OK, intent);
        } else {
            setResult(RESULT_CANCELED);
        }

        return super.SureReturn();
    }

    /****
     * 刷新指定页面信息
     *
     * @param nPageIndex
     */
    private void RefreshPageInfo(int nPageIndex) {
        getPageData(nPageIndex);
    }

    /***
     * 获取指定页面数据
     *
     * @param nPageIndex
     * @return
     */
    private int getPageData(int nPageIndex) {

        String szKeys = "";

        if (mFindKeys != null) {
            szKeys = mFindKeys.getText().toString();
        }

        /**组合参数*/
        Map<String, Object> iTem = new HashMap<String, Object>();
        iTem.put(mKeyName, szKeys);

        // 设置参数
        String szParamets = MergeRemoteParamerts(nPageIndex, mPages, iTem);

        // 获取远程数据
        mRemoteDB.getRemoteData(mRemoteAddress, szParamets, "GET", new RemoteDataService.OnRemoteDataEvent() {
            /***
             * 返回结果
             * @param szString
             */
            @Override
            public void OnResultEvent(String szString) {
                try {
                    // 转换成JSON处理
                    JSONObject json = JSON.parseObject(szString);

                    if (json.containsKey("code")) {
                        int nCode = json.getInteger("code");
                        if (nCode == 0) {
                            JSONObject data = json.getJSONObject("data");
                            JSONArray rows = data.getJSONArray("rows");
                            mPageIndex = data.getInteger("page");


                            // 设置总数
                            if (data.containsKey("total")) {
                                mPageCount = data.getInteger("total");
                            }

                            if (rows.size() > 0)
                                mItems.clear();


                        }
                    }

                } catch (JSONException ex) {

                }
            }

            /***
             * 进度展示
             * @param nStatus
             */
            @Override
            public void OnRuningState(int nStatus) {
                if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                    WaitDialog.ShowDialog(mContext, "请稍后...");
                } else {
                    WaitDialog.HideDialog();
                }
            }

            /***
             * 回调获取参数
             * @return
             */
            @Override
            public String OnGetCustomParam() {
                return null;
            }
        });

        return -1;
    }

    /***
     * 装载数据
     *
     * @param szJson
     * @return
     */
    public int LoadData(String szJson) {
        if (szJson == null)
            return -1;

        JSONArray rows = JSONArray.parseArray(szJson);

        for (int i = 0; i < rows.size(); i++) {
            JSONObject iTem = rows.getJSONObject(i);

            if (mKeyTitleName != "") {
                if (iTem.containsKey(mKeyTitleName)) {
                    // 获取Title值
                    String szTitle = iTem.getString(mKeyTitleName);

                    // 转换成JSON数据
                    String szJsonString = iTem.toJSONString();

                    Map<String, Object> iTemData = new HashMap<String, Object>();

                    iTemData.put("listTitle", szTitle);
                    iTemData.put("selectValue", szJsonString);

                    mItems.add(iTemData);
                }
            }
        }

        // 刷新数据
        if (mListView != null) {
            ChoiceView adapter = new ChoiceView(activity_search_map.this, mItems);
            mListView.setAdapter(adapter);
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Log.i("test","onItemClick1");
                    //获取条目
                    CheckableFrameLayout linearLayout = (CheckableFrameLayout) view.findViewById(R.id.ll_contain);
                    if (linearLayout.isChecked()) {
                        if (!mSelectItems.contains(i)) {
                            mSelectItems.add(i);
                        }
                    } else {
                        if (mSelectItems.contains(i)) {
                            mSelectItems.remove(i);
                        }
                    }
                }
            });

            // 选择模式
            mListView.setChoiceMode(mSelectMode);
            mListView.setAdapter(adapter);
        }

        return -1;
    }

    /***
     * 格式化参数
     *
     * @param nPageIndex
     * @param nPageSize
     * @param Paramerts
     * @return
     */
    @Override
    public String MergeRemoteParamerts(int nPageIndex, int nPageSize, Map<String, Object> Paramerts) {
        Map<String, Object> oReturn = new HashMap<>();
        if (Paramerts != null) {
            if (Paramerts.containsKey("breed_name"))
                oReturn.put("breed_name", Paramerts.get("breed_name"));
        }

        oReturn.put("breed_id", gSampleInfo.getTaskbreed());


        return super.MergeRemoteParamerts(nPageIndex, nPageSize, oReturn);
    }
}
